/*************************************************************************************************
 * CLASS: GameView.java
 * FUNCTION:Initiates the game thread and implements actual game logic
 * AUTHOR:Manori Thakur
 * ************************************************************************************************/

package com.example.android.debuggermenu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Random;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.Paint.Style;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import clientcore.GameState;
import clientresponse.ResponseBoardQuestion;

import com.example.android.debuggermenu.models.Bug;
import com.example.android.debuggermenu.models.Player;
import com.example.android.debuggermenu.models.components.Speed;

public class GameView extends SurfaceView implements SurfaceHolder.Callback { // SensorEventListener
	private static final String TAG = GameView.class.getSimpleName();

	private Activity context;
	private GameThread thread;

	private Bug bug1, bug2;
	private ArrayList<Bug> bugs;
	private Player player;

	private AlertDialog.Builder builder;
	private AlertDialog QuestionDialog;
	private LayoutInflater inflater;
	private View toastlayout;
	private Toast toast;
	private Button submit;
	private Button skip;
	private RadioButton rb0, rb1, rb2, rb3;
	private Vector<String> dialogOptions;
	private String dialogTopic;
	private String dialogTitle;

	private ImageView image;
	private Bitmap mBackgroundImage;

	private Paint mPaint;
	private Canvas canv;
	private String whichPlayer;
	private long gold = 0;
	private int questionCount = 0;
	private int lives = 3;
	private RectF rect20, rect40, rect60, rect80, rect100;
	private boolean inQuestion = false;

	private boolean collisionWithBug1, collisionWithBug2;
	private Random rand;
	private int posx = 0, posy = 0;

	private SoundPool snd;
	private int bsnd = 0;
	private int ssnd = 0;
	private int wsnd = 0;
	private SoundPoolThread soundPoolThread;

	// sensor manager used to control the accelerometer sensor.
	/*
	 * SENSOR private SensorManagerSimulator mSensorManager;
	 */

	// accelerometer sensor values.
	private float mAccelX = 0;
	private float mAccelY = 0;
	private float mAccelZ = 0;
	private int sensor = 0;
	private float[] values = null;
	private float prevAccelX = 0, prevAccelY = 0, prevAccelZ = 0;
	private float lastX = 0, lastY = 0, lastZ = 0;
	private int newX = 0, newY = 0;

	private float force = 0;
	private static float threshold = 0.02f;
	private int interval = 1000;
	private long now = 0;
	private long timeDiff = 0;
	private long lastUpdate = 0;
	private long lastShake = 0;

	public GameView(final Context context) {
		super(context);
		this.context = (Activity) context;

		rand = new Random();

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setFilterBitmap(true);
		mPaint.setTextSize(15);
		mPaint.setARGB(255, 0, 0, 255);
		mPaint.setTypeface(Typeface.SERIF);

		collisionWithBug1 = false;
		collisionWithBug2 = false;

		// setup accelerometer sensor manager.
		// Installed Open-Intents Sensor Simulator on the Android Emulator
		// Entered port and IP address in the settings
		// Reference the libray 'sensorsimulator-lib-1.1.0-rc1.jar
		// Start the simulator from the command prompt before testing
		// accelerometer on emulator
		// C:/java -jar sensorsimulator-1.1.0-rc1.jar
		/*
		 * try { mSensorManager =
		 * SensorManagerSimulator.getSystemService(context,
		 * Context.SENSOR_SERVICE); mSensorManager.connectSimulator(); } catch
		 * (Exception e) { Log.d(TAG, "Sensor Simulator not connected"); }
		 */
		// adding the callback (this) to the surface holder to intercept events
		getHolder().addCallback(this);
		// create the game loop thread
		// thread = new GameThread(getHolder(),this);

		bugs = new ArrayList<Bug>();

		this.setFocusableInTouchMode(true);

		// layout and toasts for visual responses
		inflater = this.context.getLayoutInflater();
		toastlayout = inflater.inflate(R.layout.toast_layout,
				(ViewGroup) findViewById(R.id.toast_layout_root));
		image = (ImageView) toastlayout.findViewById(R.id.image);
		toast = new Toast(this.context.getApplicationContext());
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(toastlayout);

		// Accessing the audio files stored on the SD card
		AssetManager asset = context.getAssets();

		snd = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
		try {
			bsnd = snd.load(asset.openFd("bgm4.ogg"), 0);
			ssnd = snd.load(asset.openFd("successogg.ogg"), 0);
			wsnd = snd.load(asset.openFd("wrongogg.ogg"), 0);
		} catch (IOException e) {
			Log.e("TAG",
					"IOException in constructor of GameView while loading sounds"
							+ e.toString());
		}

		// bsnd=snd.load("/mnt/sdcard/bgm4.ogg", 0);
		// ssnd=snd.load("/mnt/sdcard/successogg.ogg", 0);
		// wsnd=snd.load("/mnt/sdcard/wrongogg.ogg", 0);
		// soundPoolThread = new SoundPoolThread();
		// soundPoolThread.setRunning(true);

		// make the GamePanel focusable so it can handle events
		setFocusable(true);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.d(TAG, "Surface is being changed");
		mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, width,
				height, true);

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.d(TAG, "Surface is being created");
		Log.d(TAG, "The screen size is width: " + this.getWidth() + " height: "
				+ this.getHeight());

		thread = new GameThread(getHolder(), this);

		// Create bug1 image
		posx = rand.nextInt(this.getWidth());
		posy = rand.nextInt(this.getHeight());
		bug1 = new Bug(BitmapFactory.decodeResource(getResources(),
				R.drawable.darthvader), posx, posy);
		posx = rand.nextInt(this.getWidth());
		posy = rand.nextInt(this.getHeight());
		bug2 = new Bug(BitmapFactory.decodeResource(getResources(),
				R.drawable.drevil), posx, posy);

		if (bugs.size() < 2) {
			bugs.add(bug1);
			bugs.add(bug2);
		}

		// Create the player or character
		posx = rand.nextInt(this.getWidth() - 30);
		posy = rand.nextInt(this.getHeight() - 30);
		player = new Player(BitmapFactory.decodeResource(getResources(),
				R.drawable.oldspice), posx + 10, posy + 10);
		Resources res = context.getResources();

		mBackgroundImage = BitmapFactory
				.decodeResource(res, R.drawable.surface);

		rect20 = new RectF(getWidth() - 300, getHeight() - 40,
				getWidth() - 250, getHeight() - 30);
		rect40 = new RectF(getWidth() - 300, getHeight() - 40,
				getWidth() - 200, getHeight() - 30);
		rect60 = new RectF(getWidth() - 300, getHeight() - 40,
				getWidth() - 150, getHeight() - 30);
		rect80 = new RectF(getWidth() - 300, getHeight() - 40,
				getWidth() - 100, getHeight() - 30);
		rect100 = new RectF(getWidth() - 300, getHeight() - 40,
				getWidth() - 50, getHeight() - 30);

		snd.play(bsnd, 1, 1, 0, -1, 1);
		// soundPoolThread.start();

		// REGISTER THE SENSOR EVENT LISTENER
		// mSensorManager.registerListener(this,
		// mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
		// SensorManager.SENSOR_DELAY_GAME);

		thread.setRunning(true);
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		/*
		 * TODO determine when the surface is destroyed and what exactly needs
		 * to be shutdown or saved for when it's possibly recreated.
		 */
		Log.d(TAG, "Surface is being destroyed");
		boolean retry = true;
		while (retry) {

			// Unregister the listener when the surface is destroyed and thread
			// is ended**********************************
			/*
			 * if(mSensorManager!=null) mSensorManager.unregisterListener(this);
			 */
			// soundPoolThread.setRunning(false);

			snd.stop(bsnd);
			snd.stop(wsnd);
			snd.stop(ssnd);
			snd.release();

			// GameState.logout();
			// am.closeServer();
			// thread.join();

			retry = false;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			// delegating event handling to the bug1
			for (int i = 0; i < bugs.size(); i++) {
				(bugs.get(i)).handleActionDown((int) event.getX(),
						(int) event.getY());
			}

			player.handleActionDown((int) event.getX(), (int) event.getY());

			/*
			 * DEBUG, this is killing the game if (event.getY() > getHeight() -
			 * 50) { Log.d("onTouchEvent()","Killing the game");
			 * thread.setRunning(false); ((Activity)getContext()).finish(); }
			 * else {
			 */
			Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
			// }
		}
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			// moving the bugs
			for (int i = 0; i < bugs.size(); i++) {
				if ((bugs.get(i)).isBugTouched()) {
					(bugs.get(i)).setX((int) event.getX());
					(bugs.get(i)).setY((int) event.getY());
				}
			}

			// moving the player
			if (player.isPlayerTouched()) {
				player.setX((int) event.getX());
				player.setY((int) event.getY());
			}
		}
		if (event.getAction() == MotionEvent.ACTION_UP) {
			// touch released
			for (int i = 0; i < bugs.size(); i++) {
				if ((bugs.get(i)).isBugTouched()) {
					(bugs.get(i)).setBugTouched(false);
				}
			}

			// touch released
			if (player.isPlayerTouched()) {
				player.setPlayerTouched(false);
			}
		}
		return true;
	}

	/**
	 * Does the actual drawing of canvas
	 * 
	 * @param canvas
	 */
	public void render(Canvas canvas) {
		canv = canvas;
		whichPlayer = GameState.getUserName() + " is playing with Gold=" + gold;
		canv.drawColor(Color.WHITE);
		canv.drawBitmap(mBackgroundImage, 0, 0, mPaint);
		canv.scale((float) Game.scale * 1, (float) Game.scale * 1);

		for (int i = 0; i < bugs.size(); i++) {
			(bugs.get(i)).draw(canv);
		}

		player.draw(canv);
		mPaint.setTextAlign(Paint.Align.CENTER);
		if (gold >= 20) {
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(rect20, mPaint);
		}
		if (gold >= 40) {
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(rect40, mPaint);
		}
		if (gold >= 60) {
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(rect60, mPaint);
		}
		if (gold >= 80) {
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(rect80, mPaint);
		}
		if (gold >= 100) {
			mPaint.setStyle(Style.FILL);
			canvas.drawRect(rect100, mPaint);
		}
		canv.drawText(whichPlayer, getWidth() * 0.5f, this.getHeight() - 25,
				mPaint);

	}

	/**
	 * This is the game update method. 1)Called every tick count except when a
	 * question dialog pops up 2)Includes update physics for bug and the player
	 * based on accelerometer. 3)Detects collision 4)Handles collision and
	 * repositions bugs and the player
	 */
	public void update() {
		for (int i = 0; i < bugs.size(); i++) {
			// check collision with right wall if heading right for the bugs
			if ((bugs.get(i)).getSpeed().getxDirection() == Speed.DIRECTION_RIGHT
					&& (bugs.get(i)).getX()
							+ (bugs.get(i)).getBitmap().getWidth() / 2 >= getWidth()) {
				(bugs.get(i)).getSpeed().toggleXDirection();
			}
			// check collision with left wall if heading left for the bugs
			if ((bugs.get(i)).getSpeed().getxDirection() == Speed.DIRECTION_LEFT
					&& (bugs.get(i)).getX()
							- (bugs.get(i)).getBitmap().getWidth() / 2 <= 0) {
				(bugs.get(i)).getSpeed().toggleXDirection();
			}
			// check collision with bottom wall if heading down for the bugs
			if ((bugs.get(i)).getSpeed().getyDirection() == Speed.DIRECTION_DOWN
					&& (bugs.get(i)).getY()
							+ (bugs.get(i)).getBitmap().getHeight() / 2 >= getHeight()) {
				(bugs.get(i)).getSpeed().toggleYDirection();
			}
			// check collision with top wall if heading up for the bugs
			if ((bugs.get(i)).getSpeed().getyDirection() == Speed.DIRECTION_UP
					&& (bugs.get(i)).getY()
							- (bugs.get(i)).getBitmap().getHeight() / 2 <= 0) {
				(bugs.get(i)).getSpeed().toggleYDirection();
			}
			(bugs.get(i)).update();
		}

		// updates player position based on accelerometer
		// changes***********************************************
		/*
		 * if(mAccelX!=prevAccelX){ Log.d(TAG, "the accelx is : "+mAccelX);
		 * prevAccelX=mAccelX; newX=(int)(player.getX()+(mAccelX*2)); if((newX >
		 * 10) && (newX < (this.getWidth()-10))) //boundary check
		 * player.setX((int)newX); }
		 * 
		 * if(mAccelY!=prevAccelY){ Log.d(TAG, "the accely is : "+mAccelY);
		 * prevAccelY=mAccelY; newY=(int)(player.getY()-(mAccelY*2)); if((newY >
		 * 10) && (newY < (this.getHeight()-10)))//boundary check
		 * player.setY((int)newY); }
		 */

		/* comment out collision responses for testing */
		// check for collisions between bugs and the player
		collisionWithBug1 = checkCollisions(player, bug1);
		collisionWithBug2 = checkCollisions(player, bug2);
		handleCollision(collisionWithBug1 || collisionWithBug2);
	}

	/** Build and display question dialogue, handle user responses. */
	public void showQuestionDialog() {
		View questiondialogview = this.context.getLayoutInflater().inflate(
				R.layout.question_layout,
				(ViewGroup) findViewById(R.id.question_linearlayout1));
		builder = new AlertDialog.Builder((Activity) context);
		builder.setView(questiondialogview);

		TextView title = (TextView) questiondialogview
				.findViewById(R.id.question_text);

		title.setText(dialogTitle);

		// Set question views for different question types.
		if (ResponseBoardQuestion.question.getType() == 1) { // True/False
			for (int i = 0; i < dialogOptions.size(); i++) {
				if (i == 0) {
					rb0 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_0);
					rb0.setText(dialogOptions.get(0));
				}
				if (i == 1) {
					rb1 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_1);
					rb1.setText(dialogOptions.get(1));
				}
			}
			rb2 = (RadioButton) questiondialogview.findViewById(R.id.radio_2);
			((View) rb2).setVisibility(INVISIBLE);
			rb3 = (RadioButton) questiondialogview.findViewById(R.id.radio_3);
			((View) rb3).setVisibility(INVISIBLE);
		}
		if (ResponseBoardQuestion.question.getType() == 2) { // Multiple Choice
			for (int i = 0; i < dialogOptions.size(); i++) {
				if (i == 0) {
					rb0 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_0);
					rb0.setText(dialogOptions.get(0));
				}
				if (i == 1) {
					rb1 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_1);
					rb1.setText(dialogOptions.get(1));
				}
				if (i == 2) {
					rb2 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_2);
					rb2.setText(dialogOptions.get(2));
				}
				if (i == 3) {
					rb3 = (RadioButton) questiondialogview
							.findViewById(R.id.radio_3);
					rb3.setText(dialogOptions.get(3));
				}
			}
		}

		submit = (Button) questiondialogview.findViewById(R.id.buttonSubmit);
		skip = (Button) questiondialogview.findViewById(R.id.buttonSkip);

		/*
		 * RAYMUND LEW, May 10, 2011 Example code to use the accelerometer to
		 * detect a "shake" motion used to skip questions is interspersed
		 * throughout this function (showQuestionDialog).
		 * 
		 * CAUTION: This is example code only. Code has only been added to show
		 * the skipping of questions. The shake (accelerometer) listener is not
		 * properly registered/unregistered at the onPause, onResume, onStop
		 * points of the main Activity.
		 */

		/*
		 * Here is example code using the OpenIntents SensorSimulator. Make sure
		 * to have the simulator set up and connected to use the example code.
		 * Comment out the following code if you want to use the regular
		 * accelerometer (or if you don't want to connect the sensor simulator,
		 * since using the phone's accelerometer on the emulator is basically
		 * using nothing at all).
		 */
		// final SensorSimulatorShakeListener shakeListener =
		// SensorSimulatorShakeListener
		// .getInstance();
		// shakeListener.setContext(context);
		// shakeListener
		// .setOnShakeListener(new
		// SensorSimulatorShakeListener.OnShakeListener() {
		// @Override
		// public void onShake() {
		// QuestionDialog.dismiss();
		// // GameState.clearQuestion();
		// inQuestion = false;
		// shakeListener.stop();
		// /*
		// * RAYMUND LEW: This will make another question appear
		// * after this question is "skipped."
		// */
		// handleCollision(true);
		// }
		// });

		/*
		 * Here is example code using the phone's actual accelerometer. Code
		 * following this example should be used in a real distribution. Comment
		 * this out (and un-comment the code above) to use the OpenIntents
		 * SensorSimulator.
		 */
		final ShakeListener shakeListener = new ShakeListener(context);
		shakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {

			@Override
			public void onShake() {
				QuestionDialog.dismiss();
				// GameState.clearQuestion();
				inQuestion = false;
				shakeListener.stop();
				handleCollision(true);
			}
		});

		// Set event listeners based on question type.
		submit.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				if (ResponseBoardQuestion.question.getType() == 1) { // True/False
					if (rb0.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (0));
					if (rb1.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (1));
				}
				if (ResponseBoardQuestion.question.getType() == 2) { // Multiple
																		// Choice
					if (rb0.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (0));
					if (rb1.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (1));
					if (rb2.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (2));
					if (rb3.isChecked())
						ResponseBoardQuestion.question.setChoice((short) (3));
				}
				// If nothing selected, do nothing.
				if (ResponseBoardQuestion.question.getChoice() < 0)
					return;
				// Send user's choice to the server.
				GameState.answerQuestion();

				// Handle both correct/incorrect response conditions:
				if (ResponseBoardQuestion.question.getStatus()) {
					// 1) CORRECT
					gold = gold + 10;
					// snd.play("/mnt/sdcard/successogg.ogg");
					snd.play(ssnd, 1, 1, 0, 0, 1);
					// soundPoolThread.setPlaySuccess();

					image.setImageResource(R.drawable.successtrans);
					toast.show();
				} else {
					// 2) INCORRECT
					// snd.play("/mnt/sdcard/wrongogg.ogg");
					snd.play(wsnd, 1, 1, 0, 0, 1);
					// soundPoolThread.setPlayWrong();
					lives--;
					Log.d(TAG, "LIVES: " + lives);

					image.setImageResource(R.drawable.wrongtrans);
					toast.show();
				}

				QuestionDialog.dismiss();
				// reposition bug1 and the player
				GameState.clearQuestion();
				inQuestion = false;

				/*
				 * RAYMUND LEW: Code for skipping questions by shaking is added
				 * here.
				 */
				shakeListener.stop();
			}
		});

		skip.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				QuestionDialog.dismiss();
				// GameState.clearQuestion(); /* RAYMUND LEW: Commented out to
				// make going to the next question easier. */
				inQuestion = false;

				/*
				 * RAYMUND LEW: Code for skipping questions by shaking is added
				 * here.
				 */
				shakeListener.stop();
				/*
				 * RAYMUND LEW: Code also added here to make "skipping"
				 * questions actually skip (go to another question).
				 */
				handleCollision(true);
			}
		});
		QuestionDialog = builder.create();
		QuestionDialog.show();

		/* RAYMUND LEW: Code for skipping questions by shaking is added here. */
		shakeListener.start();
	}

	/**
	 * Uses bounding circle collision detection with a tolerance factor
	 * 
	 * @param player
	 * @param bug1
	 * @return
	 */
	public boolean checkCollisions(Player player, Bug bug1) {

		float dist = (float) Math.sqrt(((bug1.getCenterX() - player
				.getCenterX()) * (bug1.getCenterX() - player.getCenterX()))
				+ ((bug1.getCenterY() - player.getCenterY()) * (bug1
						.getCenterY() - player.getCenterY())));
		if (dist < ((bug1.getRadius() + player.getRadius()) * 0.9)) {
			return true;
		}
		return false;
	}

	/**
	 * If collision, stops the update method of the game thread and triggers
	 * Question dialog on main thread
	 * 
	 * @return
	 */
	public void handleCollision(boolean collision) {
		if (collision) {
			collisionWithBug1 = false;
			collisionWithBug2 = false;

			// Get question and options
			GameState.updateQuestion();
			dialogTopic = ResponseBoardQuestion.question.getTopic();
			dialogTitle = ResponseBoardQuestion.question.getText();
			dialogOptions = new Vector<String>(
					ResponseBoardQuestion.question.getMyOptions());

			// show the Question dialog on the main UI thread
			context.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					questionCount = questionCount + 1;
					if ((questionCount > 10) || (gold >= 100) || (lives == 0)) {
						endGame();
					} else {
						inQuestion = true;
						showQuestionDialog();
					}
				}
			});

			// reposition bug1 and the player
			reposition();
		}
	}

	public String getDialogTitle() {
		return dialogTitle;
	}

	public GameThread getThread() {
		return thread;
	}

	public void update(Observable arg0, Object arg1) {
		invalidate();
	}

	public void reposition() {
		for (int i = 0; i < bugs.size(); i++) {
			posx = rand.nextInt(this.getWidth());
			posy = rand.nextInt(this.getHeight() - 50);
			(bugs.get(i)).setX(this.getWidth() - posx);
			(bugs.get(i)).setY(this.getHeight() - posy);
		}

		posx = rand.nextInt(this.getWidth() - 30);
		posy = rand.nextInt(this.getHeight() - 30);
		player.setX(posx + 10);
		player.setY(posy + 10);

	}

	public void endGame() {
		if ((gold >= 100) && (questionCount >= 10)) {
			canv.drawText("Congrats! You are a Software Engineer Trainee!",
					getWidth() * 0.5f, this.getHeight() - 75, mPaint);
		}
		if ((lives <= 0) && (questionCount < 10)) {
			canv.drawText("Game Over", getWidth() * 0.5f,
					this.getHeight() - 75, mPaint);
		}
		if ((gold < 100) && (questionCount >= 10)) {
			canv.drawText("Try Again", getWidth() * 0.5f,
					this.getHeight() - 75, mPaint);
		}
		try {
			thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("endGame()", "Killing the game");
		thread.setRunning(false);
		((Activity) getContext()).finish();

	}

	/**
	 * Standard window-focus override. Notice focus lost so we can pause on
	 * focus lost. e.g. user switches to take a call.
	 */
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		if (!hasWindowFocus) {
			if (thread != null) {

			}
		}
	}

	/*
	 * @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO
	 * Auto-generated method stub
	 * 
	 * }
	 */

	/**
	 * SensorEventListenerMethod records the changed values of
	 * accelerometer******************************************************
	 */
	/*
	 * @Override public void onSensorChanged(SensorEvent event) { mAccelX =
	 * event.values[0]; mAccelY = event.values[1]; mAccelZ = event.values[2];
	 * 
	 * if (inQuestion == true) { now = System.currentTimeMillis();
	 * 
	 * if (lastUpdate == 0) { lastUpdate = now; lastShake = now; lastX =
	 * mAccelX; lastY = mAccelY; lastZ = mAccelZ; } else { timeDiff = now -
	 * lastUpdate; if (timeDiff > 0) { force = Math.abs(mAccelX + mAccelY +
	 * mAccelZ - lastX - lastY - lastZ) / timeDiff; Log.d(TAG, "Force: " +
	 * force); if (force > threshold) { Log.d("TAG", "Less than interval?" +
	 * (now - lastShake)); if (now - lastShake >= interval) { Log.d(TAG,
	 * "Success!!!"); QuestionDialog.dismiss(); GameState.clearQuestion();
	 * showQuestionDialog(); } lastShake = now; } lastX = mAccelX; lastY =
	 * mAccelY; lastZ = mAccelZ; lastUpdate = now; } } } }
	 */

	/**
	 * Called by onResume() method of Game activity after onCreate()/onPause()
	 * to enable sensor
	 */
	/*
	 * public void registerAccelerometer () { if(mSensorManager!=null)
	 * mSensorManager.registerListener(this,
	 * mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
	 * SensorManager.SENSOR_DELAY_GAME); }
	 */
	/**
	 * Called by onStop() and onPause() methods of Game activity to disable
	 * sensor
	 */
	/*
	 * public void unregisterAccelerometer () { if(mSensorManager!=null)
	 * mSensorManager.unregisterListener(this); }
	 */

	public long returnGold() {
		return gold;
	}

	public int returnQuestionCount() {
		return questionCount;
	}

	public int returnLives() {
		return lives;
	}
}